package com.xxx.controller;

import com.xxx.entity.Books;
import com.xxx.entity.RE;
import com.xxx.service.BookService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/book")
@Api(tags = "图书操作")
public class BookController {

    @Autowired
    BookService bookService;

    @GetMapping("/getById/{id}")
    @ApiOperation("根据ID获取图书")
    public RE getById(@PathVariable("id") Integer id){
        try {
            Books books = bookService.getById(id);
            return new RE().ok(books);
        }catch (Exception e){
            return RE.error(e.getMessage());
        }
    }

    @GetMapping("/getAll")
    @ApiOperation("获取全部图书")
    public RE getAll(){
        try {
            List<Books> booksList = bookService.getAll();
            return new RE().ok(booksList);
        }catch (Exception e){
            return RE.error(e.getMessage());
        }
    }

    @GetMapping("/getByMenuId/{menuId}")
    @ApiOperation("根据菜单ID获取图书")
    public RE getByMenuId(@PathVariable("menuId") Integer menuId){
        try {
            List<Books> booksList = bookService.getByMenuId(menuId);
            return new RE().ok(booksList);
        }catch (Exception e){
            return RE.error(e.getMessage());
        }
    }

    @PostMapping("/saveBook")
    @ApiOperation("保存图书")
    public RE saveBook(@RequestBody Books books){
        try {
            int count = bookService.saveBook(books);
            return new RE().ok(count);
        }catch (Exception e){
            return RE.error(e.getMessage());
        }
    }

    @PostMapping("/updateById")
    @ApiOperation("修改图书")
    public RE updateById(@RequestBody Books books){
        try {
            int count = bookService.update(books);
            return new RE().ok(count);
        }catch (Exception e){
            return RE.error(e.getMessage());
        }
    }

    @PostMapping("/deleteById")
    @ApiOperation(value = "根据ID删除图书（支持多个ID）,参数为数组")
    public RE deleteById(@RequestBody Integer... id){
        try {
            int count = bookService.delete(id);
            return new RE().ok(count);
        }catch (Exception e){
            return RE.error(e.getMessage());
        }
    }
}
